//
//  KZEventCell.m
//  xiaorizi
//
//  Created by kun on 15/10/25.
//  Copyright © 2015年 origin. All rights reserved.
//

#import "KZEventCell.h"
#import "UIImageView+WebCache.h"


#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height


@interface KZEventCell ()<UIWebViewDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *superViewConstraint;

@property (weak, nonatomic) IBOutlet UIView *rightView;


@property (weak, nonatomic)  UILabel *headTitleLabel;
@property (weak, nonatomic)  UILabel *headTitleSubLabel;



@property (strong,nonatomic) UIView *bgView;
@property (strong,nonatomic) UIImageView *imgView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UILabel *eventsLabel;

@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;


@end


@implementation KZEventCell





//设置webView基本属性
- (void)awakeFromNib {
    
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
    self.webView.userInteractionEnabled = NO;
    self.scrollView.delegate = self;
    [self.webView.scrollView addObserver:self forKeyPath:@"contentOffset" options:0 context:nil];

#warning 添加头部视图有问题？
   // [self createWebViewHeaderView];
    
}

//给webView添加头部视图
-(void)createWebViewHeaderView
{
    UIView* headerView = [[UILabel alloc]init];
    headerView.backgroundColor = [UIColor redColor];
    headerView.frame = CGRectMake(8, 0, SCREEN_WIDTH -16,80);
    [self.webView.scrollView addSubview:headerView];
    
   // self.webView.scrollView.contentInset = UIEdgeInsetsMake(-40, 0, 0, 0);
    
    //添加头部视图
    UILabel* headTitleLabel = [[UILabel alloc]init];
    //headView.backgroundColor = [UIColor clearColor];
    headTitleLabel.frame = CGRectMake(0, 0, SCREEN_WIDTH -16,40);
    
    _headTitleLabel = headTitleLabel;
    [headerView addSubview:_headTitleLabel];
    
    UILabel* headTitleSubLabel = [[UILabel alloc]init];
    //headView.backgroundColor = [UIColor clearColor];
    headTitleLabel.frame = CGRectMake(0, 40, SCREEN_WIDTH -16,40);
    [headTitleLabel setFont:[UIFont systemFontOfSize:12]];
    [headTitleLabel setTextColor:[UIColor grayColor]];
    _headTitleSubLabel = headTitleLabel;
    [headerView addSubview:_headTitleSubLabel];
    
    
}





- (void)setModel:(EveryDayModel *)model
{
    _model = model;
    
    
    
    
    //添加头部视图
    self.headTitleLabel.text = model.feeltitle;
    self.headTitleSubLabel.text = model.tag;
    
    
    //1 设置webView的数据
    
    NSMutableString *data_content =[NSMutableString stringWithString:model.mobileURL];
    
    //1 这里实现对webView中的图片，文字进行更改
    [data_content appendString:@"<html>"];
    [data_content appendString:@"<head>"];
    
    [data_content appendString:@"<style>img{width:100%;max-height:200px;}</style>"];
    [data_content appendString:@"<style>body{font-size:14;}</style>"];
    [data_content appendString:@"<style>table{width:100%;}</style>"];
    [data_content appendString:@"<title>webview</title>"];
    
    [self.webView loadHTMLString:data_content baseURL:[NSURL URLWithString:model.shareURL]];
    //rightView
    self.eventsLabel.text = model.feeltitle;
    self.phoneLabel.text = model.telephone;
    self.addressLabel.text = model.address;

    
    
#warning 3 这里存在问题 必须放到这里 不然其他界面继承的时候 不会加载ifneed借口实现约束更新
    self.superViewConstraint.constant = CGRectGetWidth([UIScreen mainScreen].bounds) *2;
    [self updateConstraints];
    
}

//设置滑动视图的约束
//-(void) updateConstraintsIfNeeded
//{
//    [super updateConstraintsIfNeeded];
//    self.superViewConstraint.constant = CGRectGetWidth([UIScreen mainScreen].bounds) *2;
//}


- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
    
    //调整字号
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '95%'";
    [_webView stringByEvaluatingJavaScriptFromString:str];
    
    //js方法遍历图片添加点击事件 返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    [_webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
    NSString *resurlt = [_webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    //调用js方法

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    //    NSLog(@"requestString is %@",requestString);
    
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        //        NSLog(@"image url------%@", imageUrl);
        
        if (_bgView) {
            //设置不隐藏，还原放大缩小，显示图片
            _bgView.hidden = NO;
            _imgView.frame = CGRectMake(10, 10, SCREEN_WIDTH-40, 220);
            //[_imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:LOAD_IMAGE(@"house_moren")];
            [_imgView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        }
        else
            [self showBigImage:imageUrl];//创建视图并显示图片
        
        return NO;
    }
    return YES;
}


-(void)showBigImage:(NSString *)imageUrl{
    //创建灰色透明背景，使其背后内容不可操作
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [_bgView setBackgroundColor:[UIColor colorWithRed:0.3
                                               green:0.3
                                                blue:0.3
                                               alpha:0.7]];
    [self addSubview:_bgView];
    
    //创建边框视图
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-20, 240)];
    //将图层的边框设置为圆脚
    borderView.layer.cornerRadius = 8;
    borderView.layer.masksToBounds = YES;
    //给图层添加一个有色边框
    borderView.layer.borderWidth = 8;
    borderView.layer.borderColor = [[UIColor colorWithRed:0.9
                                                    green:0.9
                                                     blue:0.9
                                                    alpha:0.7] CGColor];
    [borderView setCenter:_bgView.center];
    [_bgView addSubview:borderView];
    
    //创建关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [closeBtn setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    closeBtn.backgroundColor = [UIColor redColor];
    [closeBtn addTarget:self action:@selector(removeBigImage) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setFrame:CGRectMake(borderView.frame.origin.x+borderView.frame.size.width-20, borderView.frame.origin.y-6, 26, 27)];
    [_bgView addSubview:closeBtn];
    
    //创建显示图像视图
    _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(borderView.frame)-20, CGRectGetHeight(borderView.frame)-20)];
    _imgView.userInteractionEnabled = YES;
    
   [_imgView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    [borderView addSubview:_imgView];
    //添加捏合手势
    [_imgView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
    
}


-(void)removeBigImage
{
    _bgView.hidden = YES;
}

- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
{
    //缩放:设置缩放比例
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

    if(self.scrollView.contentOffset.x > [UIScreen mainScreen].bounds.size.width - 10)
    {
           if(self.changeCellHeightBlock)
           {
               self.changeCellHeightBlock(self);
           }
    }
    else if (self.scrollView.contentOffset.x < 10)
    {
        if(self.restoreCellHeightBlock)
        {
            self.restoreCellHeightBlock(self);
        }
    }

    
}






#pragma 添加KVO键值监控滑动的变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //在这里边添加你的代码
   if(self.webView.scrollView.contentOffset.y == 0)
   {
       self.webView.userInteractionEnabled = NO;
   }else
   {
       self.webView.userInteractionEnabled = YES;
   }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
